import 'dart:async';
import 'dart:math';

import 'package:just_audio/just_audio.dart';
import 'package:flutter/material.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_sound_elem.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';

/// 语音消息
class MsgSoundElemWidget extends StatefulWidget {
  /// 是否自己
  final bool isSelf;

  /// 是否正在播放
  final bool isPlaying;

  /// 消息
  final V2TimMessage message;

  /// 播放状态变化
  final Function(V2TimMessage message) onPlaySoundStateChange;

  const MsgSoundElemWidget({
    super.key,
    required this.isSelf,
    required this.isPlaying,
    required this.message,
    required this.onPlaySoundStateChange,
  });

  @override
  State<MsgSoundElemWidget> createState() => _MsgSoundElemWidgetState();
}

class _MsgSoundElemWidgetState extends State<MsgSoundElemWidget> {
  /// 长度
  final int charLen = 8;

  /// 是否正在播放
  late bool isPlaying;

  /// 订阅
  StreamSubscription<Object>? subscription;

  /// 消息id
  String? msgID;

  /// 语音消息
  late V2TimSoundElem stateElement;

  /// 播放器
  SoundPlayer soundPlayer = SoundPlayer();

  /// 初始状态
  @override
  void initState() {
    super.initState();

    // 初始状态
    isPlaying = widget.isPlaying;
    msgID = widget.message.msgID;
    stateElement = widget.message.soundElem!;

    // 订阅播放状态
    subscription = soundPlayer.playStateListener((PlayerState state) {
      if (state.processingState == ProcessingState.completed) {
        soundPlayer.currentPlayedMsgId = "";
        // 回调音频状态更新
        widget.onPlaySoundStateChange(widget.message);
      }
    });

    // 下载消息详情并保存
    downloadMessageDetailAndSave();
  }

  /// 释放组件
  @override
  void dispose() {
    // 停止播放
    if (isPlaying) {
      soundPlayer.stop();
      soundPlayer.currentPlayedMsgId = "";
    }
    // 取消订阅
    subscription?.cancel();

    super.dispose();
  }

  /// 父组件更新时，检查播放状态
  @override
  void didUpdateWidget(oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 更新播放状态
    setState(() {
      isPlaying = soundPlayer.currentPlayedMsgId != '' &&
          soundPlayer.currentPlayedMsgId == msgID;
    });
  }

  /// 下载消息详情并保存
  downloadMessageDetailAndSave() async {
    if (msgID != null && msgID != '') {
      if (stateElement.url == null || stateElement.url == '') {
        final response =
            await IMService.to.manager.getMessageOnlineUrl(msgID: msgID!);
        if (response.data != null) {
          widget.message.soundElem = response.data!.soundElem;
          Future.delayed(const Duration(microseconds: 10), () {
            if (mounted) {
              setState(() => stateElement = response.data!.soundElem!);
            }
          });
        }
      }
      if (!PlatformUtils().isWeb) {
        if (widget.message.soundElem!.localUrl == null ||
            widget.message.soundElem!.localUrl == '') {
          IMService.to.manager.downloadMessage(
            msgID: widget.message.msgID!,
            messageType: MessageElemType.V2TIM_ELEM_TYPE_SOUND,
          );
        }
      }
    }
  }

  /// 播放音频
  _playSound() async {
    // 正在播放则停止
    if (isPlaying) {
      soundPlayer.stop();
    } else {
      // 播放音频
      // 本地文件优先
      if (stateElement.localUrl != null) {
        soundPlayer.playLocal(localFile: stateElement.localUrl!);
      } else if (stateElement.url != null) {
        // 播放网络音频
        soundPlayer.playUrl(url: stateElement.url!);
      }

      // 设置当前播放标记
      soundPlayer.currentPlayedMsgId = msgID!;
    }

    // 回调音频状态更新
    widget.onPlaySoundStateChange(widget.message);
  }

  /// 语音组件显示长度
  double _getSoundLen() {
    double soundLen = 32;
    if (stateElement.duration != null) {
      final realSoundLen = stateElement.duration!;
      int sdLen = 32;
      // 如果音频时长大于 10 秒，每增加 0.5 秒增加一个字符长度
      if (realSoundLen > 10) {
        sdLen = 12 * charLen + ((realSoundLen - 10) * charLen / 0.5).floor();
      }
      // 如果音频时长大于 2 秒，每增加 1 秒增加一个字符长度
      else if (realSoundLen > 2) {
        sdLen = 2 * charLen + realSoundLen * charLen;
      }
      // 最小尺寸 32
      sdLen = min(sdLen, 20 * charLen);
      soundLen = sdLen.toDouble();
    }

    return soundLen;
  }

  /// 主视图
  Widget _buildView() {
    final fontStyle = TextStyle(
        fontSize: 14,
        color: widget.isSelf == true
            ? AppColors.onPrimary
            : AppColors.onSecondary);

    final borderRadius = widget.isSelf
        ? const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(2),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10))
        : const BorderRadius.only(
            topLeft: Radius.circular(2),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10));

    return GestureDetector(
      onTap: () => _playSound(),
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: widget.isSelf ? AppColors.primary : AppColors.secondary,
          borderRadius: borderRadius,
        ),
        constraints: const BoxConstraints(maxWidth: 240),
        child: Column(
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: widget.isSelf
                  ? [
                      // 语音长度
                      Container(width: _getSoundLen()),
                      // 语音时长
                      Text(
                        "''${stateElement.duration} ",
                        style: fontStyle,
                      ),
                      // 语音图标
                      isPlaying
                          ? Image.asset(
                              'assets/chat/images/play_voice_send.gif',
                              width: 16,
                              height: 16,
                            )
                          : Image.asset(
                              'assets/chat/images/voice_send.png',
                              width: 16,
                              height: 16,
                            ),
                    ]
                  : [
                      isPlaying
                          ? Image.asset(
                              'assets/chat/images/play_voice_receive.gif',
                              width: 16,
                              height: 16,
                            )
                          : Image.asset(
                              'assets/chat/images/voice_receive.png',
                              width: 16,
                              height: 16,
                            ),
                      Text(
                        " ${stateElement.duration}''",
                        style: fontStyle,
                      ),
                      Container(width: _getSoundLen()),
                    ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildView();
  }
}
